// 该组件为通用用户技能管理组件，被多个页面复用，已归类到 common 目录
<template>
  <div class="user-skill-management">
    <div class="skill-header">
      <span class="header-title">个人技能</span>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增技能
      </el-button>
    </div>

    <el-table
      ref="tableRef"
      v-loading="loading"
      :data="skillList"
      row-key="id"
      stripe
      class="sortable-table"
      @row-click="handleRowClick"
    >
      <el-table-column prop="skillName" label="技能名称" min-width="120">
        <template #default="scope">
          <div class="skill-name">
            <div class="drag-handle">⋮⋮</div>
            <div class="color-dot" :style="{ backgroundColor: scope.row.skillColor }"></div>
            {{ scope.row.skillName }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="skillLevel" label="技能等级" width="180">
        <template #default="scope">
          <div class="skill-level-container">
            <el-progress
              :percentage="scope.row.skillLevel"
              :color="scope.row.skillColor"
              :stroke-width="8"
              :text-inside="false"
              :show-text="false"
            />
            <span class="skill-level-text">{{ scope.row.skillLevel }}%</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="skillDescription" label="描述" min-width="150" show-overflow-tooltip />
      <el-table-column label="操作" width="80" align="center">
        <template #default="scope">
          <el-button
            size="small"
            type="danger"
            class="delete-btn"
            @click.stop="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="80px">
        <el-form-item label="技能名称" prop="skillName">
          <el-input v-model="formData.skillName" placeholder="请输入技能名称" />
        </el-form-item>
        <el-form-item label="技能等级" prop="skillLevel">
          <el-slider
            v-model="formData.skillLevel"
            :min="0"
            :max="100"
            show-input
            :show-input-controls="false"
          />
        </el-form-item>
        <el-form-item label="技能颜色" prop="skillColor">
          <el-color-picker v-model="formData.skillColor" @active-change="handleColorChange" />
        </el-form-item>
        <el-form-item label="技能描述" prop="skillDescription">
          <el-input
            v-model="formData.skillDescription"
            type="textarea"
            :rows="3"
            placeholder="请输入技能描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, nextTick } from 'vue'
  import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
  import { Plus } from '@element-plus/icons-vue'
  import Sortable from 'sortablejs'
  import type { UserSkill, UserSkillSaveOrUpdateParam } from '@/types/user-skill'
  import {
    getUserSkillList,
    saveOrUpdateUserSkill,
    deleteUserSkill,
    updateUserSkillSortOrder,
  } from '@/api/user-skill'

  // 响应式数据
  const loading = ref(false)
  const submitting = ref(false)
  const dialogVisible = ref(false)
  const dialogTitle = ref('新增技能')
  const skillList = ref<UserSkill[]>([])
  const formRef = ref<FormInstance>()
  const tableRef = ref()

  // 表单数据
  const formData = reactive<UserSkillSaveOrUpdateParam>({
    userId: 1, // 默认用户ID，实际应该从用户状态获取
    skillName: '',
    skillLevel: 0,
    skillColor: '#3178C6',
    skillDescription: '',
    sortOrder: 0,
  })

  // 表单验证规则
  const formRules: FormRules = {
    skillName: [{ required: true, message: '请输入技能名称', trigger: 'blur' }],
    skillLevel: [{ required: true, message: '请设置技能等级', trigger: 'change' }],
  }

  // 初始化拖拽排序
  const initSortable = () => {
    nextTick(() => {
      const tbody = tableRef.value?.$el?.querySelector('.el-table__body-wrapper tbody')
      if (tbody) {
        Sortable.create(tbody, {
          handle: '.drag-handle',
          animation: 150,
          onEnd: async (evt: Sortable.SortableEvent) => {
            const { oldIndex, newIndex } = evt
            if (oldIndex !== newIndex && oldIndex !== undefined && newIndex !== undefined) {
              // 更新本地数据
              const movedItem = skillList.value.splice(oldIndex, 1)[0]
              skillList.value.splice(newIndex, 0, movedItem)

              // 更新排序到后端
              await updateSortOrder()
            }
          },
        })
      }
    })
  }

  // 加载技能列表
  const loadSkillList = async () => {
    loading.value = true
    try {
      const result = await getUserSkillList(1) // 默认用户ID
      skillList.value = result
      // 重新初始化拖拽
      initSortable()
    } catch (error) {
      console.error('加载技能列表失败:', error)
    } finally {
      loading.value = false
    }
  }

  // 更新排序
  const updateSortOrder = async () => {
    try {
      const updateParams = skillList.value.map((item, index) => ({
        id: item.id!,
        userId: item.userId,
        skillName: item.skillName,
        skillLevel: item.skillLevel,
        skillColor: item.skillColor,
        skillDescription: item.skillDescription,
        sortOrder: index + 1,
      }))

      await updateUserSkillSortOrder(updateParams)
      ElMessage.success('排序更新成功')
    } catch (error) {
      console.error('更新排序失败:', error)
      // 重新加载数据
      await loadSkillList()
    }
  }

  // 点击行进入编辑
  const handleRowClick = (row: UserSkill) => {
    dialogTitle.value = '编辑技能'
    Object.assign(formData, row)
    dialogVisible.value = true
  }

  // 新增技能
  const handleAdd = () => {
    dialogTitle.value = '新增技能'
    resetFormData()
    dialogVisible.value = true
    //随机一个颜色
    formData.skillColor = '#' + Math.floor(Math.random() * 16777215).toString(16)
  }

  // 删除技能
  const handleDelete = async (row: UserSkill) => {
    try {
      await ElMessageBox.confirm('确定要删除这个技能吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })

      await deleteUserSkill(row.id!)
      ElMessage.success('删除成功')
      await loadSkillList()
    } catch (error) {
      if (error !== 'cancel') {
        console.error('删除技能失败:', error)
      }
    }
  }

  // 提交表单
  const handleSubmit = async () => {
    if (!formRef.value) return

    try {
      await formRef.value.validate()
      submitting.value = true

      // 如果是新增，设置排序为最后
      if (!formData.id) {
        formData.sortOrder = skillList.value.length + 1
      }

      await saveOrUpdateUserSkill(formData)
      ElMessage.success(formData.id ? '更新成功' : '新增成功')

      dialogVisible.value = false
      await loadSkillList()
    } catch (error) {
      console.error('保存技能失败:', error)
    } finally {
      submitting.value = false
    }
  }

  // 对话框关闭处理
  const handleDialogClose = () => {
    formRef.value?.resetFields()
    resetFormData()
  }

  // 重置表单数据
  const resetFormData = () => {
    Object.assign(formData, {
      id: undefined,
      userId: 1,
      skillName: '',
      skillLevel: 0,
      skillColor: '#3178C6',
      skillDescription: '',
      sortOrder: 0,
    })
  }

  // 处理颜色变化
  const handleColorChange = (color: string | null) => {
    if (color) {
      formData.skillColor = color
    }
  }

  // 页面加载时获取数据
  onMounted(() => {
    loadSkillList()
  })
</script>

<style scoped>
  .user-skill-management {
    height: 100%;
  }

  .skill-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
  }

  .header-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }

  .skill-name {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .drag-handle {
    cursor: move;
    color: #909399;
    font-size: 12px;
    user-select: none;
    padding: 2px;
  }

  .drag-handle:hover {
    color: #409eff;
  }

  .color-dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    flex-shrink: 0;
  }

  .skill-level-container {
    display: flex;
    align-items: center;
    gap: 12px;
    width: 100%;
  }

  .skill-level-container .el-progress {
    flex: 1;
  }

  .skill-level-text {
    font-size: 12px;
    font-weight: 600;
    color: #606266;
    min-width: 35px;
    text-align: right;
  }

  .sortable-table :deep(.el-table__row) {
    cursor: pointer;
  }

  .sortable-table :deep(.el-table__row:hover) {
    background-color: #f5f7fa;
  }

  .delete-btn {
    margin: 0;
  }

  /* 拖拽时的样式 */
  .sortable-table :deep(.sortable-ghost) {
    opacity: 0.5;
    background: #f0f9ff;
  }

  .sortable-table :deep(.sortable-chosen) {
    background: #e1f5fe;
  }

  /* 对话框样式 */
  .skill-dialog :deep(.el-dialog__header) {
    padding: 20px 20px 10px;
    border-bottom: 1px solid #ebeef5;
  }

  .skill-dialog :deep(.el-dialog__title) {
    font-size: 18px;
    font-weight: 600;
    color: #303133;
  }

  .skill-form {
    padding: 20px;
  }

  .level-input {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }

  .level-preview {
    display: flex;
    justify-content: flex-start;
  }

  .color-input {
    display: flex;
    align-items: center;
    gap: 12px;
  }

  .color-preview-large {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 80px;
    height: 32px;
    border-radius: 6px;
    border: 1px solid #dcdfe6;
    position: relative;
  }

  .color-text {
    color: #fff;
    font-size: 12px;
    font-weight: 500;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
  }

  .sort-tip {
    margin-left: 12px;
    font-size: 12px;
    color: #909399;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding: 15px 20px 20px;
    border-top: 1px solid #ebeef5;
  }

  /* 表格样式优化 */
  :deep(.el-table) {
    border-radius: 8px;
  }

  :deep(.el-table__header-wrapper) {
    border-top-left-radius: 8px;
    border-top-right-radius: 8px;
  }

  :deep(.el-table__body-wrapper) {
    border-bottom-left-radius: 8px;
    border-bottom-right-radius: 8px;
  }

  :deep(.el-table .el-table__cell) {
    padding: 12px 0;
  }

  :deep(.el-table tbody tr:hover > td) {
    background-color: #f8f9fa !important;
  }

  :deep(.el-progress-bar__outer) {
    border-radius: 10px;
  }

  :deep(.el-progress-bar__inner) {
    border-radius: 10px;
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    .skill-header {
      flex-direction: column;
      gap: 12px;
      align-items: stretch;
    }

    .header-title {
      justify-content: center;
    }

    .skill-dialog {
      width: 95% !important;
      margin: 5vh auto !important;
    }
  }
</style>
